﻿using EBA.Framework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Text;
using System.Threading;

namespace EBA.WindowsServices
{
    /// <summary>
    /// <see cref="IWindowsService"/>托管中心
    /// </summary>
    [Serializable]
    public class WindowsServiceHosting : BundleRuntime<IWindowsService>
    {
        public WindowsServiceHosting()
            : this(null)
        {
 
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configFile"></param>
        public WindowsServiceHosting(string configFile = null)
            : base(configFile)
        {

            Channels.RegisterIpcChannel(Constants.HostingServiceChannelName);
            RemotingServices.Marshal(this, Constants.HostingObjectUri, typeof(WindowsServiceHosting));
        }

        /// <summary>
        /// 启动所有已安装的服务
        /// </summary>
        public void Start()
        {
            foreach (var bundle in this.Configuration.Framework.Bundles.AsEnumerable)
            {
                this.Start(bundle.Id);
            }
        }

        /// <summary>
        /// 默认输出
        /// </summary>
        IWindowsServiceOutput Output = new WindowsServiceOutput();


        /// <summary>
        /// 插件启动时
        /// </summary>
        /// <param name="context"></param>
        protected override void OnBundleStarting(IBundleContext context)
        {

            var service = context.Bundle as IWindowsService;

            //  service.Output =  // remots this.Output;
        }


        /// <summary>
        /// 停止所有已安装的服务
        /// </summary>
        public void Stop()
        {
 
            foreach (var context in this.BundleContextes)
            {
                context.Bundle.Stop();
            }
        }

        internal IpcServerChannel Channel { get; set; }


        protected override void FreeManagedResources()
        {
            base.FreeManagedResources();
            if (this.Channel != null)
            {
                ChannelServices.UnregisterChannel(this.Channel);
                this.Channel = null;
            }
        }
    }



}
